<template>
	<view>
		<button @click="tableToExcel">导出一个表来看</button>
		<view>{{ successTip }}</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				successTip: ''
			}
		},
		methods: {
			uuid() {
				return 'xxx-xxx-xxx'.replace(/[xy]/g, c => {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8)
					return v.toString(16)
				})
			},

			tableToExcel() {
				// 要导出的json数据
				const jsonData = [{
						name: '科比',
						phone: '123456',
						email: '科比@163.com'
					},
					{
						name: '科比',
						phone: '123456',
						email: '科比@163.com'
					},
					{
						name: '科比',
						phone: '123456',
						email: '科比@163.com'
					},
					{
						name: '科比',
						phone: '123456',
						email: '科比@163.com'
					},
				]
				// 列标题
				let worksheet = 'sht1'
				let str =
					'<tr><td style="text-align: center">姓名</td><td style="text-align: center">电话</td><td style="text-align: center">邮箱</td></tr>'
				// 循环遍历，每行加入tr标签，每个单元格加td标签
				for (let i = 0; i < jsonData.length; i++) {
					str += '<tr>'
					for (let item in jsonData[i]) {
						// 增加\t为了不让表格显示科学计数法或者其他格式
						str += `<td>${jsonData[i][item] + '\t'}</td>`
					}
					str += '</tr>'
				}
				// 下载的表格模板数据

				let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
        xmlns:x="urn:schemas-microsoft-com:office:excel" 
        xmlns="http://www.w3.org/TR/REC-html40">
        <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
				// 下载模板
				// #ifdef APP-PLUS
				this.appExportFile(template)
				// #endif
				// 下载模板
				// #ifdef MP-WEIXIN
				this.wxExportFile(template)
				// #endif
			},

			// 导出文件到手机 fileData:要写入到文件的数据，返回参数为文档路径
			appExportFile(fileData, documentName = '项目Excel文件') {
				// PUBLIC_DOCUMENTS: 程序公用文档目录常量
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
					let rootObj = fs.root,
						fullPath = rootObj.fullPath
					console.log('开始导出数据********')
					// 创建文件夹
					rootObj.getDirectory(documentName, {
						create: true
					}, dirEntry => {
						// 创建文件,防止重名
						let fileName = 'excel' + this.uuid() + '.xlsx'
						dirEntry.getFile(fileName, {
							create: true
						}, fileEntry => {
							fileEntry.createWriter(writer => {
								writer.onwritestart = res => console.log('正在导出')
								//  /storage/emulated/0指的就是系统路径
								let pathStr = fullPath.replace('/storage/emulated/0', '')
								// 成功导出数据
								writer.onwrite = res => {
									// 文件路径
									let filePath = res.target.fileName
									uni.hideLoading()
									setTimeout(() => {
										console.log('成功导出')
										this.successTip = `文件位置：${filePath}`

										uni.openDocument({
											filePath,
											success: res => console
												.log('打开文档成功'),
											fail: err => console.log(
												err)
										})
									}, 500)
								}
								// 写入内容
								writer.write(fileData)
							}, err => console.log(err.message))
						})
					})
				})
			},

			wxExportFile(template, documentName = '项目Excel文件') {
				const fs = uni.getFileSystemManager()
				// 创建文件名字, 防止重名
				let filePath = uni.env.USER_DATA_PATH + '/' + (documentName + this.uuid()) + '.xls'
				fs.writeFile({
					filePath,
					data: template,
					encoding: 'utf8',
					success: res => {

						uni.openDocument({
							filePath,
							showMenu: true, //是否显示右上角菜单
							success: res => console.log('打开文档成功。文件位置', filePath),
							fail: err => console.log(err)
						})
					},
					fail: err => console.info(err)
				})
			}
		}
	}
</script>